//
//  AMBucketObjectsTableView.m
//  AWSMobile
//
//  Created by James on 14-10-31.
//  Copyright (c) 2014年 Siemens. All rights reserved.
//

#import "AMBucketObjectsTableView.h"
#import "AMBucketObjectCell.h"

#import "AMUploadObjectTableView.h"
#import "AMConstants.h"
#import "AMFunctions.h"

#import <AWSiOSSDKv2/S3.h>
#import <Bolts/BFTask.h>
#import <Bolts/BFExecutor.h>

@interface AMBucketObjectsTableView ()

@property (nonatomic) NSMutableArray *contents;
//@property (nonatomic) NSMutableArray *sectionIndexTitle;
@property UIBarButtonItem *addButton;
@property BOOL viewIsVisable;

@property AWSS3ListObjectsRequest *listObjectsRequest;
@property AWSS3DeleteObjectRequest *deleteObjectRequest;
@property AWSS3GetObjectRequest *downloadObjectRequest;
@property AWSS3PutObjectRequest *uploadObjectRequest;

@end

@implementation AMBucketObjectsTableView

#pragma mark - Setter and getter
- (NSMutableArray *)contents
{
    if (!_contents)
    {
        _contents = [[NSMutableArray alloc] init];
    }
    return _contents;
}

#pragma mark - Life cycle
- (void)viewWillAppear:(BOOL)animated
{
    self.title = [NSString stringWithFormat:@"Loading %@",_bucketName];
    
    _addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addObject)];
    self.navigationItem.rightBarButtonItems = @[_refreshButton,_addButton];
    
    [self refreshBucketObjects:nil];
    
    _viewIsVisable = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    _viewIsVisable = NO;
    self.navigationItem.rightBarButtonItems = @[_refreshButton];
    if (_listObjectsRequest)
    {
        [_listObjectsRequest cancel];
        _listObjectsRequest = nil;
    }
    if (_deleteObjectRequest)
    {
        [_deleteObjectRequest cancel];
        _deleteObjectRequest = nil;
    }
    if (_uploadObjectRequest)
    {
        [_uploadObjectRequest cancel];
        _uploadObjectRequest = nil;
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
//    self.sectionIndexTitle = [[NSMutableArray alloc] initWithCapacity:1];
    self.contents = [[NSMutableArray alloc] initWithCapacity:1];
    
    UIView *view = [[UIView alloc] init];
    [self.tableView setTableFooterView:view];
    
    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    self.tableView.sectionIndexColor = [UIColor colorWithHexString:@"36b2af"];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.contents count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = @"ContentCell";
    
//    [tableView registerClass:[AMBucketObjectCell class] forCellReuseIdentifier:CellIdentifier];
    AMBucketObjectCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    AWSS3Object *ob = _contents[indexPath.row];
    
    NSString *objectKey = ob.key;
    NSRange range = [objectKey rangeOfString:@"/"];
    if (range.location == NSNotFound)
    {
        cell.objectName.text = ob.key;
        cell.objectIcon.image = [UIImage imageNamed:@"文件.png"];
    }
    else
    {
        cell.objectName.text = [objectKey substringToIndex:range.location];
        cell.objectIcon.image = [UIImage imageNamed:@"文件夹.png"];
    }
    
    cell.detailLabel.text = @"";
    if ([self checkDownloadStateAtIndex:indexPath])
    {
        cell.detailLabel.text = @"downloaded";
    }
    
    cell.objectIndicatorColor.backgroundColor = [UIColor randomIndicatorColor];
    cell.indexPath = indexPath;
    cell.delegate = self;
    cell.dataSource = self;
    
    return cell;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - Alert view delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (_viewIsVisable)
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - Actions

- (void)networkStarted
{
    UIActivityIndicatorView *iView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    UIBarButtonItem *iBarItem = [[UIBarButtonItem alloc] initWithCustomView:iView];
    [iView startAnimating];
    self.navigationItem.rightBarButtonItem = iBarItem;
}

- (void)networkStopped
{
    self.navigationItem.rightBarButtonItem = _refreshButton;
}

- (BOOL)checkDownloadStateAtIndex:(NSIndexPath *)indexPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    AWSS3Object *object = _contents[indexPath.row];
    NSString *path = [[paths objectAtIndex:0] stringByAppendingFormat:@"/%@",object.key];
    if ([[NSFileManager defaultManager] fileExistsAtPath:path])
    {
        return YES;
    }
    return NO;
}

- (IBAction)refreshBucketObjects:(UIBarButtonItem *)sender
{
    
    [self networkStarted];
    
    if (!_listObjectsRequest)
    {
        _listObjectsRequest = [[AWSS3ListObjectsRequest alloc] init];
        _listObjectsRequest.bucket = _bucketName;
    }
    __block typeof(self) weakSelf = self;
    [[[AWSS3 defaultS3] listObjects:_listObjectsRequest] continueWithExecutor:[BFExecutor mainThreadExecutor] withBlock:^id(BFTask *task){
        if (!task.error)
        {
            [weakSelf.contents removeAllObjects];
//            [weakSelf.sectionIndexTitle removeAllObjects];
            
            weakSelf.contents = [[(AWSS3ListObjectsOutput *)task.result contents] mutableCopy];
//            NSMutableArray *containner = [[NSMutableArray alloc] initWithCapacity:1];
//            for (AWSS3Object *object in contents)
//            {
//                NSString *first = [[object.key substringToIndex:1] uppercaseString];
//                NSString *last = [[[[[weakSelf.contents lastObject] firstObject] key] substringToIndex:1] uppercaseString];
//                if (!last)
//                {
//                    [containner addObject:object];
//                    [weakSelf.contents addObject:[containner copy]];
//                    [weakSelf.sectionIndexTitle addObject:first];
//                }
//                else if ([last isEqualToString:first])
//                {
//                    [containner addObject:object];
//                }
//                else
//                {
//                    weakSelf.contents[weakSelf.contents.count - 1] = [containner copy];
//                    [containner removeAllObjects];
//                    [containner addObject:object];
//                    [weakSelf.contents addObject:[containner copy]];
//                    [weakSelf.sectionIndexTitle addObject:first];
//                }
//            }
//            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf networkStopped];
                [weakSelf.tableView reloadData];
                weakSelf.title = _bucketName;
//            });
        }
        else if (task.error.code != - 999)
        {
            [weakSelf networkStopped];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Notice" message:@"Do not have right for this bucket" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
        }
        return nil;
    }];
}


- (void)addObject
{
    UINavigationController *uploadNavView = [self.storyboard instantiateViewControllerWithIdentifier:@"UploadNavView"];
    AMUploadObjectTableView *uploadView = (AMUploadObjectTableView *)uploadNavView.topViewController;
    uploadView.existContents = _contents;
    uploadView.bucket = _bucketName;
    [self presentViewController:uploadNavView animated:YES completion:nil];
}

#pragma mark - Cell dataSource
- (NSInteger)numberOfButtonsInSwipeableCellAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self checkDownloadStateAtIndex:indexPath])
    {
        return 1;
    }
    return 2;
}

- (NSString *)titleForButtonAtIndex:(NSInteger)index inCellAtIndexPath:(NSIndexPath *)indexPath
{
    return @"";
}
- (UIImage *)imageForButtonAtIndex:(NSInteger)index inCellAtIndexPath:(NSIndexPath *)indexPath
{
    if (index == 0)
    {
        return [UIImage imageNamed:@"delete_object"];
    }
    else
    {
        return [UIImage imageNamed:@"download_object"];
    }
    
}
- (UIColor *)backgroundColorForButtonAtIndex:(NSInteger)index inCellAtIndexPath:(NSIndexPath *)indexPath
{
    if (index == 0)
    {
        return [UIColor colorWithHexString:@"f26c6c"];
    }
    else
    {
        return [UIColor colorWithHexString:@"97c2b3"];
    }
}

- (UIColor *)textColorForButtonAtIndex:(NSInteger)index inCellAtIndexPath:(NSIndexPath *)indexPath
{
    return [UIColor blackColor];
}

#pragma mark - Cell delegate
- (void)swipeableCell:(AMBucketObjectCell *)cell didSelectButtonAtIndex:(NSInteger)index
{
    [cell closeCell:YES];
    if (index == 0)
    {
        NSString *key = cell.objectName.text;
        __block typeof(self) weakSelf = self;
        if (!_deleteObjectRequest)
        {
            _deleteObjectRequest = [[AWSS3DeleteObjectRequest alloc] init];
            _deleteObjectRequest.bucket = _bucketName;
        }
        if (key)
        {
            _deleteObjectRequest.key = key;
            
            [self networkStarted];
            
            [[[AWSS3 defaultS3] deleteObject:_deleteObjectRequest] continueWithExecutor:[BFExecutor mainThreadExecutor] withBlock:^id(BFTask *task){
                [weakSelf networkStopped];
                if (!task.error)
                {
                    [weakSelf.contents removeObjectAtIndex:cell.indexPath.row];
                    [weakSelf.tableView deleteRowsAtIndexPaths:@[cell.indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                }
                else
                {
                    NSLog(@"%@",task.error);
                }
                return nil;
            }];
        }

    }
    else
    {
        NSString *key = cell.objectName.text;
        if (key)
        {
            if (!_downloadObjectRequest)
            {
                _downloadObjectRequest = [[AWSS3GetObjectRequest alloc] init];
                _downloadObjectRequest.bucket = _bucketName;
            }
            _downloadObjectRequest.key = key;
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *path = [[paths objectAtIndex:0] stringByAppendingFormat:@"/%@",key];
            _downloadObjectRequest.downloadingFileURL = [NSURL fileURLWithPath:path];
            
            [self networkStarted];
            
            __block typeof(self) weakSelf = self;
            [[[AWSS3 defaultS3] getObject:_downloadObjectRequest] continueWithExecutor:[BFExecutor mainThreadExecutor] withBlock:^id(BFTask *task){
                [weakSelf networkStopped];
                if (!task.error)
                {
                    [self.tableView reloadRowsAtIndexPaths:@[cell.indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
                }
                else
                {
                    NSLog(@"%@",task.error);
                }
                
                return nil;
            }];
        }

    }
}

- (void)swipeableCellDidClose:(DNSSwipeableCell *)cell
{
    
}

- (void)swipeableCellDidOpen:(DNSSwipeableCell *)cell
{
    
}
@end
